import ProSelect from "@/components/ProSelect";
import { AntdModalProps } from "@/hooks/useAntdModal";
import { addCodeupAppDeployTask, queryCodeupAppLink, queryCodeupReleasePlan } from "@/service/deliver";
import { useRequest } from "ahooks";
import { Form, Input, message, Modal, Radio, Select, SelectProps, Table, Tabs } from "antd";
import { ColumnsType } from "antd/lib/table";
import { useEffect, useState } from "react";
import ReleasePlanSelect from "./ReleasePlanSelect";


const SubAppList = ({ env, miniAppList, onMiniAppChange }: any) => {
    const [miniApp, setMiniApp] = useState(miniAppList)
    const columns: ColumnsType = [
        {
            title: '标题',
            render(_) {
                return <span>{_.name}</span>
            }
        },
        {
            title: '版本',
            render(_, row, index) {
                // console.log(`${payload.env}IterationId`)
                return <ReleasePlanSelect onChange={(e) => {
                    const newVal = [...miniApp]
                    newVal[index][`${env}IterationId`] = e
                    setMiniApp([...newVal])
                }} value={_[`${env}IterationId`]} id={_.appId} />
            }
        }
    ]
    useEffect(() => {
        onMiniAppChange(miniApp)
    }, [])
    return <Table rowKey="id" pagination={false} size='small' dataSource={miniAppList} columns={columns} />
}

const DeployApp = ({ modalProps, closeModal, form, payload }: AntdModalProps) => {
    const { run, data } = useRequest<any>(queryCodeupAppLink, { manual: true })
    const [miniAppList, setMiniAppList] = useState([]);
    const [miniApp, setMiniApp] = useState({});
    console.log({ payload })
    useEffect(() => {
        if (modalProps.open) {

            run({ id: payload.id }).then(res => {
                // @ts-ignore
                const records: any[] = res.records;
                setMiniAppList([...records])
                // setTimeout(()=>{

                //     form.setFieldValue('miniApp', records)
                // },1000)
                // console.log('sss', records)
            })
        }
    }, [modalProps.open])

    const onOk = async () => {
        const data = form.getFieldsValue();
        data.env = data.env.join(',')
        console.log(form.getFieldsValue())
        await addCodeupAppDeployTask({ ...data, miniApp })
        message.success('save suc')
        closeModal();
    }
    const onMiniAppChange = (env, data) => {
        const _miniApp = { ...miniApp };
        _miniApp[env] = data
        setMiniApp({ ..._miniApp })
    }
    return <Modal width={600} destroyOnClose {...modalProps} onOk={onOk}>
        <Form form={form} initialValues={{ buildType: 1 }}>
            <Form.Item hidden name='id' />
            <Form.Item hidden name='iterationId' />
            <Form.Item hidden name='version' />
            <Form.Item hidden name='enName' />
            <Form.Item label='部署迭代' name='iterationId' rules={[{
                message: '请选择部署迭代',
                required: true
            }]}>
                <ReleasePlanSelect onChange={(e: any, ee: any) => {
                    form.setFieldValue('version', ee.item.version);
                    form.setFieldValue('enName', ee.item.enName);
                    console.log('sss', e, ee)
                }} id={payload.id} />
            </Form.Item>
            <Form.Item label='部署环境' name='env' wrapperCol={{ span: 16 }} rules={[{
                required: true,
                message: '部署环境'
            }]}>
                <Select placeholder='清选择部署环境' mode='multiple' options={[{ label: '开发环境', value: 'dev' }, { label: '测试环境', value: 'test' }]} />
            </Form.Item>
            {
                payload.type !== '2' && <>
                    <Form.Item hidden={payload.type === '2'} label='构建类型' name='buildType'>
                        <Radio.Group>
                            <Radio value={1}>更新配置</Radio>
                            <Radio value={2}>重新构建</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item noStyle shouldUpdate={(a, b) => a.env != b.env}>
                        {({ getFieldValue }) => {
                            const env = getFieldValue('env')
                            const items = [];
                            if (!env) {
                                return null
                            }
                            if (env.includes('dev')) {
                                items.push({
                                    label: '开发环境',
                                    forceRender: true,
                                    children: <SubAppList env='dev' onMiniAppChange={(data) => onMiniAppChange('dev', data)} miniAppList={miniAppList} />,
                                    key: 'dev'
                                })
                            }
                            if (env.includes('test')) {
                                items.push({
                                    label: '测试环境',
                                    forceRender: true,

                                    children: <SubAppList env='test' onMiniAppChange={(data) => onMiniAppChange('test', data)} miniAppList={miniAppList} />,
                                    key: 'test'
                                })
                            }
                            return <Tabs items={items} />
                        }}
                    </Form.Item>

                </>
            }



        </Form>

    </Modal>
}
export default DeployApp;